<template>
  <view class="login-container">
    <view class="login-header">
      <image class="logo" src="/static/share.jpeg" mode="aspectFit"></image>
      <view class="app-name">{{ apiConfig.webTitle }}</view>
      <view class="app-slogan">专业金融服务平台</view>
    </view>

    <view class="login-form">
      <view class="form-content">
        <view class="form-item">
          <u-icon name="account" size="24" color="#999"></u-icon>
          <input class="form-input" v-model="formData.name" placeholder="请输入姓名" maxlength="20" />
        </view>

        <view class="form-item">
          <u-icon name="file-text" size="24" color="#999"></u-icon>
          <input class="form-input" v-model="formData.idNumber" placeholder="请输入身份证号" maxlength="18" />
        </view>

        <view class="form-item">
          <u-icon name="lock" size="24" color="#999"></u-icon>
          <view class="form-input-group">
            <input class="form-input" v-model="formData.password" placeholder="请输入6以上位交易密码" type="password"
              maxlength="6" inputmode="numeric" pattern="[0-9]*" />
          </view>
        </view>
      </view>

      <view class="form-actions">
        <!-- <view class="remember-password">
          <checkbox v-model="formData.remember" color="#1989fa" />
          <text>记住密码</text>
        </view> -->
        <view class="forgot-password" @click="navigateTo('forgot')" v-if="false">忘记密码？</view>
      </view>

      <button class="login-btn" @click="handleLogin">登录</button>
      <view class="register-section">
        <text>还没有账号？</text>
        <text class="register-link" @click="navigateTo('register')">立即注册</text>
      </view>
    </view>

    <view class="login-footer">
      <view class="agreement-section">
        <checkbox-group v-model="formData.agreement" @change="handleAgreementChange">
          <checkbox color="#1989fa" />
        </checkbox-group>
        <text class="agreement-text">登录即代表您已同意
          <text class="link-text" @click="viewAgreement('register_agreement')">《用户协议》</text>
          和
          <text class="link-text" @click="viewAgreement('privacy_agreement')">《隐私政策》</text>
        </text>
      </view>
    </view>
  </view>
</template>

<script>
import {apiConfig} from '@/utils/apiConfig'
export default {
  computed: {
    apiConfig() {
      return apiConfig
    }
  },
  data() {
    return {
      showPassword: false,
      formData: {
        name: '',
        idNumber: '',
        password: '',
        remember: false,
        agreement: false
      },
      loading: false,
    }
  },
  onLoad() {
    // 如果已经登录，跳转到首页
    if (this.$store.getters.token) {
      this.$u.route({
        url: '/pages/home/index'
      });
    } else {
    }
  },
  methods: {
    handleAgreementChange(e) {
      console.log('e', e)
      this.formData.agreement = !this.formData.agreement
    },
    viewAgreement(type) {
      uni.navigateTo({
        url: '/pages/contract/agreement?type=' + type
      })
    },
    togglePasswordVisibility() {
      this.showPassword = !this.showPassword;
    },
    checkIdNumber(idNumber) {
        // 正则表达式验证身份证格式
        const reg = /^(?:\d{15}|\d{17}[\dX])$/;
        if (!reg.test(idNumber)) {
            console.error('身份证号码格式不正确');
            return false;
        }

        // 如果是18位身份证，进行校验位验证
        if (idNumber.length === 18) {
            const weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
            const checkDigits = '10X98765432';
            let sum = 0;

            for (let i = 0; i < 17; i++) {
                sum += idNumber[i] * weights[i];
            }

            const checkDigit = checkDigits[sum % 11];
            if (checkDigit !== idNumber[17]) {
                console.error('身份证号码校验位不正确');
                return false;
            }
        }

        console.log('身份证号码有效');
        return true;
    },
    handleLogin() {
      // 表单验证
      if (!this.formData.name) {
        return uni.showToast({
          title: '请输入姓名',
          icon: 'none'
        });
      }

      if (!this.formData.idNumber || !this.checkIdNumber(this.formData.idNumber)) {
        return uni.showToast({
          title: '请输入正确的身份证号',
          icon: 'none'
        });
      }

      if (!this.formData.password || this.formData.password.length !== 6) {
        return uni.showToast({
          title: '请输入6位交易密码',
          icon: 'none'
        });
      }

      if (!this.formData.agreement) {
        return uni.showToast({
          title: '请阅读并同意用户协议和隐私政策',
          icon: 'none'
        });
      }

      // 登录
      this.loading = true;
      uni.showLoading({
        title: '登录中...'
      });


       this.$store.dispatch('Login', this.formData).then((res) => {
            this.loading = false;
            uni.hideLoading();

            // 登录成功
            uni.showToast({
              title: '登录成功',
              icon: 'success'
            });

            // 获取用户信息
            this.$store.dispatch('GetUserInfo').then((userRes) => {
              // 跳转到首页
              setTimeout(() => {
                console.debug('REDIRECT_PATH', uni.getStorageSync('REDIRECT_PATH'))
                if (uni.getStorageSync('REDIRECT_PATH')) {
                  uni.navigateTo({
                    url: uni.getStorageSync('REDIRECT_PATH')
                  })
                } else {
                  uni.switchTab({
                    url: '/pages/home/index',
                    success: () => {
                    },
                    fail: (err) => {
                      uni.showToast({
                        title: '跳转失败，请重试',
                        icon: 'none'
                      });
                    }
                  });
                }
              }, 1500);
            }).catch(userErr => {
              uni.showToast({
                title: '获取用户信息失败，请重试',
                icon: 'none'
              });
            });
          }).catch(error => {
            this.loading = false;
            uni.hideLoading();

            // 尝试提取更详细的错误信息
            let errorMsg = '登录失败，请稍后再试';
            if (error) {
              if (typeof error === 'string') {
                errorMsg = error;
              } else if (error.message) {
                errorMsg = error.message;
              } else if (error.errMsg) {
                errorMsg = error.errMsg;
              }
            }

            uni.showToast({
              title: errorMsg,
              icon: 'none',
              duration: 3000
            });
          });
    },

    navigateTo(page) {
      if (page === 'register') {
        uni.navigateTo({
          url: '/pages/register/index'
        });
      } else if (page === 'forgot') {
        uni.navigateTo({
          url: '/pages/forgot/index'
        });
      }
    }
  }
}
</script>

<style lang="scss">
.login-container {
  min-height: 100vh;
  background-color: #fff;
  display: flex;
  flex-direction: column;
}

.login-header {
  padding: 100rpx 0 60rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.logo {
  width: 120rpx;
  height: 120rpx;
  margin-bottom: 20rpx;
}

.app-name {
  font-size: 40rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 10rpx;
}

.app-slogan {
  font-size: 28rpx;
  color: #999;
}

.login-form {
  padding: 0 50rpx;
}

.form-content {
  margin-bottom: 30rpx;
}

.form-item {
  display: flex;
  align-items: center;
  height: 100rpx;
  border-bottom: 1px solid #eee;
  margin-bottom: 30rpx;
}

.form-input {
  flex: 1;
  height: 100%;
  font-size: 30rpx;
  color: #333;
  padding: 0 20rpx;
}

.eye-icon {
  padding: 0 10rpx;
}

.form-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 50rpx;
}

.remember-password {
  display: flex;
  align-items: center;
  font-size: 26rpx;
  color: #666;
}

.remember-password text {
  margin-left: 10rpx;
}

.forgot-password {
  font-size: 26rpx;
  color: #1989fa;
}

.login-btn {
  height: 90rpx;
  background-color: #1989fa;
  color: #fff;
  font-size: 32rpx;
  font-weight: 500;
  border-radius: 45rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 30rpx;
}

.register-section {
  display: flex;
  justify-content: center;
  font-size: 28rpx;
  color: #666;
  margin-bottom: 50rpx;
}

.register-link {
  color: #1989fa;
  margin-left: 10rpx;
}

.login-footer {
  margin-top: auto;
  padding: 0 50rpx 50rpx;
}

.agreement-section {
  display: flex;
  align-items: center;
  justify-content: center;
}

.agreement-text {
  font-size: 24rpx;
  color: #999;
  margin-left: 10rpx;
}

.link-text {
  color: #1989fa;
}
</style>
